package com.example.controller;

import cn.hutool.json.JSONObject;
import com.example.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("repeat")
public class RepeatTokenController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 提交订单令牌的缓存key
     */
    public static final String SUBMIT_ORDER_TOKEN_KEY = "order:submit:%s:%s";


    /**
     * 下单前获取令牌用于防重提交
     *
     * @return
     */
    @GetMapping("token")
    public JSONObject getOrderToken() {
        JSONObject jsonObject = new JSONObject();
        //获取登录账户
        long accountNo = 10000L;
        //随机获取32位的数字+字母作为token
        String token = CommonUtil.getStringNumRandom(32);
        StringJoiner joiner1 = new StringJoiner("");
        joiner1.add("test").add(accountNo + "").add(token);
        //key的组成
        String key = joiner1.toString();
        //令牌有效时间是30分钟
        redisTemplate.opsForValue().set(key, String.valueOf(Thread.currentThread().getId()), 30, TimeUnit.MINUTES);
        jsonObject.set("repeatToken", token);
        return jsonObject;
    }


}
